<template>
	<view>
		<!-- 地图 -->
		<view class="page-body">
			<view class="page-section page-section-gap">
				<map id="map" style="width: 100%; height: 500px;" :latitude="mapCenter.latitude"
					:longitude="mapCenter.longitude" :scale='15' :markers="markers" :enable-3D='true'
					:show-compass="true" :show-location="true">
				</map>
			</view>
		</view>

		<!-- 悬浮按钮 -->
		<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			:direction="direction" @trigger="trigger" @fabClick="fabClick" />

		<!-- 手风琴（只会保留一个的打开状态） -->
		<uni-section title="手风琴效果（只会保留一个的打开状态）" type="line">
			<uni-collapse accordion v-model="accordionVal" @change="change">
				<uni-collapse-item title="手风琴效果">
					<view class="content">
						<text class="text">手风琴效果同时只会保留一个组件的打开状态，其余组件会自动关闭。</text>
					</view>
				</uni-collapse-item>
				<uni-collapse-item title="手风琴效果">
					<view class="content">
						<text class="text">手风琴效果同时只会保留一个组件的打开状态，其余组件会自动关闭。</text>
					</view>
				</uni-collapse-item>
				<uni-collapse-item title="手风琴效果">
					<view class="content">
						<text class="text">手风琴效果同时只会保留一个组件的打开状态，其余组件会自动关闭。</text>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</uni-section>

		<!-- 下拉框 -->
		<uni-data-select v-model="value" :localdata="range" @change="fabChange"></uni-data-select>

		<!-- 分页 -->
		<!-- 表格 -->
		<view class="uni-container">
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="150" align="center">日期</uni-th>
					<uni-th width="150" align="center">姓名</uni-th>
					<uni-th align="center">地址</uni-th>
					<uni-th width="204" align="center">设置</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td>{{ item.date }}</uni-td>
					<uni-td>
						<view class="name">{{ item.name }}</view>
					</uni-td>
					<uni-td align="center">{{ item.address }}</uni-td>
					<uni-td>
						<view class="uni-group">
							<button class="uni-button" size="mini" type="primary">修改</button>
							<button class="uni-button" size="mini" type="warn">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box">
				<uni-pagination :total="total" :current="pageCurrent" :page-size="pageSize" @change="change"
					show-icon />
			</view>
		</view>
		<!-- 回到顶部 -->
		<button v-show="showBackTopBtn" @click="backToTop" class="back-top-btn">回到顶部</button>

		<!-- 加入购物车 -->
		<view class="container">
			<!-- 商品列表 -->
			<view class="goods-list">
				<view v-for="(item, index) in 5" :key="index" class="goods-item">
					<image :src="item.image" class="goods-img" mode="aspectFill"></image>
					<view class="add-btn" @tap="addToCart($event, item)">加入购物车</view>
				</view>
			</view>

			<!-- 购物车图标 -->
			<view class="cart-icon" @tap="goToCart">
				<image src="/static/uni.png" mode="aspectFill"></image>
				<view class="badge">{{cartCount}}</view>
			</view>

			<!-- 动画容器 -->
			<view class="animation-wrap">
				<view v-for="(anim, index) in animations" :key="index" :class="['ball', anim.animate ? 'active' : '']"
					:style="{
		              left: anim.x + 'px',
		              top: anim.y +'px'
		            }"></view>
			</view>
		</view>

	</view>
</template>

<script>
	import tableData from '/pages/test1/tableData.js'
	export default {
		components: { // 引入模板

		},

		data() {
			return {
				// 地图
				mapCenter: {
					latitude: 0,
					longitude: 0
				},
				markers: [],
				controls: [], // 路线
				includePoints: [], //

				// 假设的终点位置
				destination: {
					latitude: 35,
					longitude: 115.5
				},
				scale: 0,

				// 悬浮按钮
				title: 'uni-fab',
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'vertical',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				content: [{
						iconPath: '/static/image.png',
						selectedIconPath: '/static/c1.png',
						text: '相册',
						active: false
					},
					{
						iconPath: '/static/home.png',
						selectedIconPath: '/static/c2.png',
						text: '首页',
						active: false
					},
					{
						iconPath: '/static/star.png',
						selectedIconPath: '/static/c3.png',
						text: '收藏',
						active: false
					}
				],

				// 手风琴只保留一个开启状态
				accordionVal: '1',

				// 下拉框
				value: 1,
				range: [{
						value: 0,
						text: "篮球"
					},
					{
						value: 1,
						text: "足球"
					},
					{
						value: 2,
						text: "游泳"
					},
				],

				// 分页
				pageCurrent: 1, // 当前页
				pageSize: 10, // 每页数据量
				total: 0, // 数据总量
				searchVal: '',
				loading: false,
				tableData: [], // 全部数据

				// 回到顶部
				showBackTopBtn: false,
				scrollTop: 0,

				// 加入购物车
				goodsList: [{}, {}], // 你的商品数据
				cartCount: 0,
				animations: []
			}
		},
		onReady() {},
		onBackPress() {
			if (this.$refs.fab.isShow) {
				this.$refs.fab.close()
				return true
			}
			return false
		},
		onLoad() {
			this.getMyLocation(); // 设置地图
			this.getData(1, this.searchVal) // 获取表格数据
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// 当滚动距离大于一定值时显示回到顶部按钮
			console.log(this.scrollTop)
			if (this.scrollTop > 300) {
				this.showBackTopBtn = true;
			} else {
				this.showBackTopBtn = false;
			}
		},
		methods: {
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i])
			},
			// 多选
			selectionChange(e) {
				console.log(e.detail.index)
				this.selectedIndexs = e.detail.index
			},
			// 分页触发
			change(e) {
				this.$refs.table.clearSelection()
				this.selectedIndexs.length = 0
				this.getData(e.current)

				this.pageCurrent = e.current;
				console.log('当前页:', this.pageCurrent);
				console.log(e.type === "current" ? "具体页数" : e.type === "next" ? "下一页" : e.type === "prev" ? "上一页" : "错误");
			},
			// 搜索
			search() {
				this.getData(1, this.searchVal)
			},
			// 获取数据
			getData(pageCurrent, value = '') {
				this.loading = true
				this.pageCurrent = pageCurrent
				this.request({
					pageSize: this.pageSize,
					pageCurrent: pageCurrent,
					value: value,
					success: res => {
						// console.log('data', res);
						this.tableData = res.data
						this.total = res.total
						this.loading = false
					}
				})
			},
			request(options) {
				const {
					pageSize,
					pageCurrent,
					success,
					value
				} = options
				let total = tableData.length
				let data = tableData.filter((item, index) => {
					const idx = index - (pageCurrent - 1) * pageSize
					return idx < pageSize && idx >= 0
				})
				if (value) {
					data = []
					tableData.forEach(item => {
						if (item.name.indexOf(value) !== -1) {
							data.push(item)
						}
					})
					total = data.length
				}

				setTimeout(() => {
					typeof success === 'function' &&
						success({
							data: data,
							total: total
						})
				}, 500)
			},
			// 回到顶部
			backToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},

			getMyLocation() {

				/* uni.setStorage({
					key: 'ceshi',
					data: {
						data: 123,
						time: 1222
					}
				}) */
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						// 设置地图中心为当前位置
						this.mapCenter.latitude = res.latitude;
						this.mapCenter.longitude = res.longitude;
						console.log('当前纬度：' + res.latitude);
						console.log('当前经度：' + res.longitude);
						// 添加当前位置的标记
						this.markers.push({
							id: 1,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '/static/location.png', // 当前位置图标路径
							title: '当前位置图标',
							width: 30,
							height: 30
						});

						// 添加终点位置的标记
						this.markers.push({
							id: 2,
							latitude: this.destination.latitude,
							longitude: this.destination.longitude,
							iconPath: '/static/location.png', // 终点位置图标路径
							title: '终点位置图标',
							width: 30,
							height: 30
						});
						// this.controls = this.includePoints = this.markers;
					},
					fail: (err) => {
						console.log('获取位置失败', err);
					}
				});
			},


			// 悬浮按钮
			trigger(e) {
				console.log(e)
				this.content[e.index].active = !e.item.active
				uni.showModal({
					title: '提示',
					content: `您${this.content[e.index].active ? '选中了' : '取消了'}${e.item.text}`,
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定')
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			},
			fabClick() {
				uni.showToast({
					title: '点击了悬浮按钮',
					icon: 'none'
				})
			},
			/* switchBtn(hor, ver) {
				this.horizontal = hor
				this.vertical = ver
				this.$forceUpdate()
			}, */

			fabChange(e) {
				console.log("e:", e);
			},


			// 加入购物车
			async addToCart(e, item) {
				// 1. 获取点击位置
				const {
					top: btnTop,
					left: btnLeft
				} = await this.getElRect(e.currentTarget)
				console.log('btnTop:',btnTop)
				// 2. 创建动画元素
				const animItem = {
					x: btnLeft,
					y: btnTop,
					animate: false
				}
				this.animations.push(animItem)

				// 3. 获取目标位置（购物车位置）
				const cartPos = await this.getElRect('.cart-icon')

				// 4. 启动动画
				this.$nextTick(() => {
					animItem.animate = true
					animItem.x = cartPos.left - 20
					animItem.y = cartPos.top - 20

					// 5. 动画完成处理
					setTimeout(() => {
						this.animations = this.animations.filter(a => a !== animItem)
						this.cartCount++
					}, 500)
				})
			},

			// 获取元素位置
			getElRect(selector) {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery().in(this)
					query.select(selector).boundingClientRect(res => {
						resolve(res)
					}).exec()
				})
			},

			goToCart() {
				// 跳转购物车页面
			}
		},



		watch: {},
		props: { //  传入进来的参数
			// val: Number,
			// kaos_xq_time:String
		},
		computed: { // 计算属性

		},
		created() { // 实例创建完成后被立即调用

		},
		mounted() { // 替换后调用
		},
	}
</script>

<style lang="scss">
	// @import '@/common/uni-ui.scss';
	// 悬浮按钮
	.warp {
		padding: 10px;
	}

	.button {
		margin-bottom: 10px;
	}

	// 手风琴
	.content {
		padding: 15px;
	}


	.text {
		font-size: 14px;
		color: #666;
		line-height: 20px;
	}

	// 表格和分页
	.uni-group {
		display: flex;
		align-items: center;
	}

	// 加入购物车
	/* 基础样式 */
	.container {
		position: relative;
	}

	.cart-icon {
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		width: 100rpx;
		height: 100rpx;
	}

	.badge {
		position: absolute;
		right: -10rpx;
		top: -10rpx;
		background: red;
		color: white;
		border-radius: 50%;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		line-height: 40rpx;
	}

	/* 动画元素 */
	.animation-wrap {
		position: fixed;
		pointer-events: none;
	}

	.ball {
		position: absolute;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: #ff5500;
		opacity: 0;
		transition: all 0.5s cubic-bezier(0.5, -0.5, 1, 1);
	}

	.ball.active {
		opacity: 1;
		transform: translate(0, 0) scale(0.5);
	}
</style>